"use client";

import * as React from "react";

import { type DropdownMenuProps } from "@radix-ui/react-dropdown-menu";

import { LineHeightPlugin } from "@platejs/basic-styles/react";
import { DropdownMenuItemIndicator } from "@radix-ui/react-dropdown-menu";
import { CheckIcon, WrapText } from "lucide-react";
import { useEditorRef, useSelectionFragmentProp } from "platejs/react";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/plate/ui/dropdown-menu";

import { ToolbarButton } from "./toolbar";

export function LineHeightToolbarButton(props: DropdownMenuProps) {
  const editor = useEditorRef();
  const { defaultNodeValue, validNodeValues: values = [] } =
    editor.getInjectProps(LineHeightPlugin);

  const value = useSelectionFragmentProp({
    defaultValue: defaultNodeValue,
    getProp: (node) =&gt; node.lineHeight,
  });

  const [open, setOpen] = React.useState(false);

  return (
    &lt;DropdownMenu open={open} onOpenChange={setOpen} modal={false} {...props}&gt;
      &lt;DropdownMenuTrigger asChild&gt;
        &lt;ToolbarButton pressed={open} tooltip="Line height" isDropdown&gt;
          &lt;WrapText /&gt;
        &lt;/ToolbarButton&gt;
      &lt;/DropdownMenuTrigger&gt;

      &lt;DropdownMenuContent className="min-w-0" align="start"&gt;
        &lt;DropdownMenuRadioGroup
          value={value}
          onValueChange={(newValue) =&gt; {
            editor
              .getTransforms(LineHeightPlugin)
              .lineHeight.setNodes(Number(newValue));
            editor.tf.focus();
          }}
        &gt;
          {values.map((value) =&gt; (
            &lt;DropdownMenuRadioItem
              key={value}
              className="*:first:[span]:hidden min-w-[180px] pl-2"
              value={value}
            &gt;
              <span>
                &lt;DropdownMenuItemIndicator&gt;
                  &lt;CheckIcon /&gt;
                &lt;/DropdownMenuItemIndicator&gt;
              </span>
              {value}
            &lt;/DropdownMenuRadioItem&gt;
          ))}
        &lt;/DropdownMenuRadioGroup&gt;
      &lt;/DropdownMenuContent&gt;
    &lt;/DropdownMenu&gt;
  );
}
